<template>
  <div class="comment-container">
    <div class="type-title">评论({{ commentList?.length }})</div>
    <div class="comment-list-warp" v-loading="isLoading">
      <div class="comment-item" v-for="item in commentList" :key="item.id">
        <div class="comment-info">
          <div class="user-info">
            <el-avatar :size="30" :src="getCommentUser(item.user_id)?.avatar" />
            <span class="user-name">{{ getCommentUser(item.user_id)?.name }}</span>
          </div>
          <div class="time">{{ item.updated_at }}</div>
        </div>
        <div class="comment-content">
          {{ item.content }}
        </div>
        <div class="comment-action">
          <el-button
            text
            v-if="usePermission('file.delete') || item.user_id === getUserInfo.id"
            @click.stop="handleDelete(item)"
            ><i class="iconfont icongis_shanchu"></i>删 除</el-button
          >
        </div>
      </div>
      <el-empty v-if="!commentList" description="暂无评论"></el-empty>
    </div>
    <div class="comment-input-warp">
      <div class="user-info-warp">
        <el-avatar :size="30" :src="getUserInfo.avatar"></el-avatar>
      </div>
      <div class="input-warp">
        <el-form
          :ref="(el:object) => { formRef = el }"
          :model="formData"
          :rules="rules"
          @submit.native.prevent
          @keypress.enter="handleSubmit"
        >
          <el-form-item label-width="0" label="" prop="content">
            <el-input
              :rows="4"
              type="textarea"
              placeholder="请输入内容"
              v-model="formData.content"
              maxlength="400"
              resize="none"
              show-word-limit
            />
          </el-form-item>
        </el-form>
        <el-button color="#6C52EA" @click.stop="handleSubmit">发表</el-button>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, watch, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

import { getCommentList, newCommentData, deleteCommentData } from '@/apis/system/docComment'
import { userStore } from '@/store/user'
import { storeToRefs } from 'pinia'
import { usePermission } from '@/hooks/usePermission'

const userData = userStore()

/**
 * @desc:获取人员信息
 * @param {Array} search 搜索
 */
onMounted(async () => {
  await userData.getUserData()
})

const props = defineProps({
  fileData: {
    type: Object,
    default: () => {}
  }
})

const rules = {
  content: [{ required: true, message: '请输入评论', trigger: 'blur' }]
}

/**
 *
 * @desc:获取登录用户信息
 */
const getUserInfo = computed(() => {
  return JSON.parse(localStorage.getItem('user') as string) || ''
})

/**
 * @desc: 获取评论
 */
const pageId = ref<number>()
const isLoading = ref(false)
const commentList = ref<IcommentList[]>()
const formData = ref({
  content: ''
})
interface IcommentList {
  content: string
  created_at: string
  deleted_at: string
  id: number
  page_id: number
  state: number
  status: number
  updated_at: string
  user_department_id: number
  user_id: number
  user_name: string
}
const getData = () => {
  isLoading.value = true
  let params = {
    page_id: pageId.value
  }
  console.log(pageId.value, 'pageId.value###')
  getCommentList(params).then((res) => {
    if (!res) return
    let arr: any = []
    arr = res
    arr.forEach((element: IcommentList) => {
      element.created_at = new Date(
        +new Date(new Date(element.created_at).toJSON()) + 8 * 3600 * 1000
      )
        .toISOString()
        .replace(/T/g, ' ')
        .replace(/\.[\d]{3}Z/, '')
    })
    // commentList.value = arr.filter((item) => item.page_id === )
    commentList.value = arr
    isLoading.value = false
  })
}

/**
 * @desc:获取评论人员信息
 * @param {Array} search 搜索
 */
const { userlistData } = storeToRefs(userData)
const getCommentUser = computed(() => (id: number) => {
  return userlistData.value.find((item) => {
    return item.id === id
  })
})

/**
 * @desc: 发布提交
 */
const formRef = ref()
const handleSubmit = () => {
  if (formRef.value) {
    formRef.value.validate((valid: boolean) => {
      if (!valid) return
      const reqData = {
        content: formData.value.content,
        page_id: pageId.value,
        user_id: getUserInfo.value.id
      }
      newCommentData(reqData)
        .then((res) => {
          if (!res) return
          formData.value.content = ''
          isLoading.value = true
          getData()
          ElMessage({
            type: 'success',
            message: '发布成功'
          })
        })
        .catch(() => {
          ElMessage('服务器内部错误')
        })
        .finally(() => {
          isLoading.value = false
        })
    })
  }
}

/**
 * @desc: 删除评论
 */
const handleDelete = (item: IcommentList) => {
  deleteCommentData(item.id)
    .then((res) => {
      if (!res) return
      isLoading.value = true
      getData()
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
    })
    .catch(() => {
      ElMessage('服务器内部错误')
    })
    .finally(() => {
      isLoading.value = false
    })
}

watch(
  () => props.fileData,
  (newVal) => {
    if (newVal.url !== 'folder') {
      pageId.value = newVal?.id
      getData()
    }
  },
  { immediate: true }
)
</script>
<style lang="less" scoped>
.comment-container {
  width: 100%;
  height: auto;
  padding: 0 10px;
  box-sizing: border-box;
  .type-title {
    font-size: 1.2em;
    padding: 10px 0;
  }
  .comment-list-warp {
    width: 100%;
    height: auto;
    .comment-item {
      // max-width: 1052px;
      .comment-info {
        display: flex;
        align-items: center;
        height: 40px;
        justify-content: space-between;
        .user-info {
          display: flex;
          align-items: center;
          padding: 0 10px;
          .user-name {
            margin-left: 10px;
          }
        }
        .time {
          color: #999;
        }
      }
      .comment-content {
        height: auto;
        // max-width: 1052px;
        padding: 10px 0 10px 52px;
      }
      .comment-action {
        // max-width: 1052px;
        padding: 0px 0 0px 52px;
      }
    }
  }
  .comment-input-warp {
    width: 100%;
    display: flex;
    .user-info-warp {
      padding: 10px;
      box-sizing: border-box;
    }
    .input-warp {
      flex-grow: 1;
      // max-width: 1000px;
    }
  }
  .no-auth-tips {
    padding: 20px;
    box-sizing: border-box;
    .info {
      display: flex;
      padding: 10px;
    }
  }
}
</style>
